package org.abettor.angleworm.i18n;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.abettor.util.Environment;

/**
 * 国际化支持类，单例模式
 * @author shawn
 */
public class Translator
{
	private static final String PATH_PREFIX = "conf" + File.separator + "language" + File.separator;
	private static final String PATH_SURFIX = ".properties";
	private static Translator translator = null;
	private static byte[] locker = new byte[0];
	private String language;
	private Properties properties;

	/**
	 * 构造国际化支持类实例
	 * @param language
	 * @throws IOException 
	 */
	protected Translator(String language) throws IOException
	{
		switchToLanguage(language);
	}

	/**
	 * 尝试获取已经配置并实例化过的国际化支持类实例
	 * @throws IOException
	 */
	public static Translator getInstance() throws IOException
	{
		return Translator.initialize(null);
	}

	/**
	 * 根据指定的语言获取国际化支持类的唯一实例
	 * @param language
	 * @throws IOException 
	 */
	public static Translator initialize(String language) throws IOException
	{
		synchronized (locker)
		{
			if(translator == null)
			{
				if(language != null)
				{
					translator = new Translator(language);
				}
				else
				{
					return null;
				}
			}
			else if(language == null)
			{
				return translator;
			}
			else if(translator.language == null || ! translator.language.equals(language))
			{
				translator.switchToLanguage(language);
			}
		}

		return translator;
	}

	/**
	 * 切换当前国际化支持类实例支持的语言
	 * @param language
	 * @throws IOException 
	 */
	public synchronized void switchToLanguage(String language) throws IOException
	{
		properties = new Properties();
		String path = Environment.getFilePath(PATH_PREFIX + language + PATH_SURFIX);
		File file = new File(path);
		if(! file.exists())
		{
			throw new IOException("File " + path + " not found.");
		}

		InputStream is = null;
		try
		{
			is = new FileInputStream(file);
			properties.load(is);
		}
		catch (FileNotFoundException e)
		{
			throw e;
		}
		finally
		{
			if(is != null)
			{
				is.close();
			}
		}

		this.language = language;
	}

	/**
	 * 根据内容标识获取当前语言下的文本内容
	 * @param key
	 */
	public String getString(String key)
	{
		String val = properties.getProperty(key);
		if(val == null)
		{
			return "";
		}

		return val;
	}

	/**
	 * 获取当前支持的语言
	 */
	public synchronized String getCurrentLanguage()
	{
		return language;
	}
}
